#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 19-6-25 下午10:55
# @Author  : Tom
# @Site    : 
# @File    : orders.py
# @Software: PyCharm
from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from meiduo_admin.serilizers import OrderSerilizer, OrderDetailSerilizer
from meiduo_admin.utils import PageNumber_User
from orders.models import OrderInfo


class OrderView(ModelViewSet):
    # 添加序列化器和查询集
    serializer_class = OrderSerilizer
    queryset = OrderInfo.objects.all().order_by("-create_time")
    # 指定分页类
    pagination_class = PageNumber_User
    permission_classes = [IsAdminUser, ]

    # 制定查询集
    def get_queryset(self):
        # 获取关键词 , queryset必须为查询列表，不能单为对象
        keyword = self.request.query_params.get("keyword")
        if keyword == "" or keyword is None:
            queryset = OrderInfo.objects.order_by("order_id")
        else:
            queryset = OrderInfo.objects.filter(order_id=keyword)
        return queryset

    @action(methods=['action'], detail=True)
    def getdetailView(self, request, pk):
        infor = OrderInfo.objects.get(order_id=pk)
        ser = OrderDetailSerilizer(infor)
        return Response(ser.data)

    def ordersstatus(self, request, pk):
        status = request.data.get("status")
        order = OrderInfo.objects.get(pk=pk)
        order.status = status
        order.save()
        ser = self.get_serializer(order)
        return Response(ser.data)
